<?php

namespace we;

use think\db\Query;
use think\facade\Request;

class ExtendQuery extends Query
{
    /**
     * 分析表达式（可用于查询或者写入操作）
     * @access public
     * @return array
     */
    public function parseOptions(): array
    {
        $options = $this->getOptions();

        // 获取数据表
        if (empty($options['table'])) {
            $options['table'] = $this->getTable();
        }

        if (!isset($options['where'])) {
            $options['where'] = [];
        } elseif (isset($options['view'])) {
            // 视图查询条件处理
            $this->parseView($options);
        }

        foreach (['data', 'order', 'join', 'union'] as $name) {
            if (!isset($options[$name])) {
                $options[$name] = [];
            }
        }

        if (!isset($options['strict'])) {
            $options['strict'] = $this->connection->getConfig('fields_strict');
        }

        foreach (['master', 'lock', 'fetch_sql', 'array', 'distinct', 'procedure'] as $name) {
            if (!isset($options[$name])) {
                $options[$name] = false;
            }
        }

        foreach (['group', 'having', 'limit', 'force', 'comment', 'partition', 'duplicate', 'extra'] as $name) {
            if (!isset($options[$name])) {
                $options[$name] = '';
            }
        }

        if (isset($options['page'])) {
            // 根据页数计算limit
            [$page, $listRows] = $options['page'];
            $page              = $page > 0 ? $page : 1;
            $listRows          = $listRows ?: (is_numeric($options['limit']) ? $options['limit'] : 20);
            $offset            = $listRows * ($page - 1);
            $options['limit']  = $offset . ',' . $listRows;
        }

        // start
        $table_list = [
            'ymq_zhnc_system_menu',
            'ymq_zhnc_region',
        ];

        if (!in_array($options['table'], $table_list) && !is_array($options['table'])) {
            if (!empty($options['alias'])) {
                $alias_field = current($options['alias']) . '.uniacid';
            } else {
                $alias_field = $options['table'] . '.uniacid';
            }
            $options['where']['AND'][] = [$alias_field, '=', config('site.uniacid')];
            $options['data']['uniacid'] = config('site.uniacid');
        }
        // end

        $this->options = $options;
        return $options;
    }
}
